package L01;
//线程安全


public class T12 {

    public static int count=0;

    public static void main (String[] args) throws InterruptedException {
        Object locker=new Object ();
        Thread t1=new Thread (()->{
            for (int i = 0; i < 50000; i++) {
                synchronized (locker){
                    count++;
                }

            }
        });
        Thread t2=new Thread (()->{
            for (int i = 0; i < 50000; i++) {
                //synchronized  加锁语句，执行步骤不会分离，直到离开该字段为止
                //其他线程调用到正在加锁的语句，阻塞等待执行结束
                //括号内写入类名，为了区分是否是对同一过程进行加锁
                synchronized (locker){
                    count++;
                }
            }
        });

        t1.start ();
        t2.start ();

        //保证上述两个线程已经执行完
        t1.join ();
        t2.join ();

        //加的结果不符合预期
        //加的步骤有先后，两个线程同时运行会导致相加步骤混乱
        //线程的随机调度机制会导致线程调度的混乱

        System.out.println ("count: "+count);
    }

}
